app.controller("invoiceBatchController",function ($scope,$controller,$location,invoiceBatchService,recordPaymentService,taskInfoService) {

    $controller('baseController',{$scope:$scope});
    $controller("indexController",{$scope:$scope});

    $scope.searchEntity = {};


    $scope.findPage = function (pageNum, pageSize) {

        if (pageNum == null) pageNum = 1;

        if (pageSize == null) pageSize = 10;

        if (startTime != null) $scope.searchEntity.startTime = startTime;

        if (endTime != null) $scope.searchEntity.endTime = endTime;

        invoiceBatchService.findPage(pageNum,pageSize,$scope.searchEntity).success(function (response) {

            if (response.code == 200){

                //获取发票批次列表
                $scope.invoiceBatchList = response.data;

                $scope.paginationConf.totalItems = response.total;


            } else {
                alert(response.msg)
            }

        });

    };

    //全选 、全不选
    $scope.allCheck = function (event) {

        $scope.selectIds = [];


        if (invoiceBatchList > 0) invoiceBatchList = [];

        if (event.target.checked){

            for (var i = 0; i < $scope.invoiceBatchList.length; i++) {

                $scope.invoiceBatchParamList.push($scope.invoiceBatchList[i]);

            }
        } else {
            $scope.invoiceBatchParamList = [];
        }
    };

    //更新发票批次状态 - 发票审核
    $scope.updateInvoiceStatus = function (invoiceBatchStatus,index) {

        console.log(index);


        if (index != null){//单个审核

            $scope.invoiceBatchParamList = [];

            $scope.invoiceBatchParamList.push($scope.invoiceBatchList[index]);

        }else {

            for (var i = 0; i < $scope.selectIds.length; i++) {

                $scope.invoiceBatchParamList.push($scope.invoiceBatchList[$scope.selectIds[i]]);

            }

        }

        console.log($scope.invoiceBatchParamList);

        if ($scope.invoiceBatchParamList.length == 0) {
            alert("您未选择发票");
            return;
        }


        if (!confirm("您确认修改吗？")) return;
      
        invoiceBatchService.updateInvoiceStatus(invoiceBatchStatus,$scope.invoiceBatchParamList).success(function (response) {
            
            if (response.code == 200){

                alert(response.msg);

                $scope.reloadList();

            } else {
                alert(response.msg);
            }

            $scope.selectIds = [];

            $scope.invoiceBatchParamList = [];
        })
    };

    //监控发票批次状态
    $scope.$watch("searchEntity.invoiceStatus",function (newValue, oldValue) {

        if (newValue == null) return;

        $scope.reloadList();
    });

    //重置条件查询参数
    $scope.resetSearchEntity = function () {

        $scope.searchEntity = {};

        $scope.reloadList();

    };

    //根据发票编号获取发票明细
    $scope.findOne = function () {

        var applyNumber = $location.search()['applyNumber'];

        if (applyNumber == null || applyNumber.length == 0){

            alert("参数丢失");
            return;
        }
        
        invoiceBatchService.findOne(applyNumber).success(function (reponse) {

            if (reponse.code == 200){

                $scope.entity = reponse.data;

            }else {
                alert(reponse.msg);
            }

        })

    };
    //获取发票明细
    $scope.findInfo = function () {

        var applyNumber = $location.search()['applyNumber'];

        if (applyNumber == null || applyNumber.length == 0){

            alert("参数丢失");
            return;
        }

        invoiceBatchService.findInfo(applyNumber).success(function (reponse) {

            if (reponse.code == 200){

                $scope.batchList = reponse.data.batchList;
                $scope.taskList = reponse.data.taskList;
                $scope.taskInfoList = reponse.data.taskInfoList;
                $scope.userList = reponse.data.userList;

                //用户信息
                let userList = $scope.userList;
                $scope.userList_five = [];
                for (let i = 0; i < userList.length; i++) {
                    if ($scope.userList_five.length >= 5) {
                        break;
                    }
                    $scope.userList_five[i] = userList[i];
                }

                //结算批次
                let batchList = $scope.batchList;
                $scope.batchList_five = [];
                for (let i = 0; i < $scope.batchList.length; i++) {
                    if ($scope.batchList_five.length >= 5) {
                        break;
                    }
                    $scope.batchList_five[i] = batchList[i];
                }

                console.log(batchList)

                //任务列表
                let taskInfoList = $scope.taskInfoList;
                $scope.taskInfoList_five = [];
                for (let i = 0; i < $scope.taskInfoList.length; i++) {
                    if ($scope.taskInfoList_five.length >= 5) {
                        break;
                    }
                    $scope.taskInfoList_five[i] = taskInfoList[i];
                }


                //任务批次
                let taskList = $scope.taskList;
                $scope.taskList_five = [];
                for (let i = 0; i < $scope.taskList.length; i++) {
                    if ($scope.taskList_five.length >= 5) {
                        break;
                    }
                    $scope.taskList_five[i] = taskList[i];
                }

                console.log(taskList)
            }

        })
    };

    $scope.totalUnitPrice = function (invoiceInfoList) {

        var totalUnitPrice = 0;

        for (var i = 0; i < invoiceInfoList.length; i++) {

           var invoiceInfo = invoiceInfoList[i];

           var unitPrice = invoiceInfo.unitPrice;

            totalUnitPrice = totalUnitPrice + unitPrice;

           console.log("单价：" + unitPrice);

        }

        return totalUnitPrice;
    };

    $scope.totalTaxAmount = function (invoiceInfoList) {

        var totalTaxAmount = 0;

        for (var i = 0; i < invoiceInfoList.length; i++) {

            var invoiceInfo = invoiceInfoList[i];


            var taxAmount = invoiceInfo.taxAmount;

            totalTaxAmount = totalTaxAmount + taxAmount;


            console.log("税额：" + taxAmount);
        }

        return totalTaxAmount;
    };

    //获取打款记录列表
    $scope.findBatchInfo = function(batchNo){

        let pageNum = 1;

        let pageSize = 1000;

        $scope.searchEntity.batchNumber = batchNo;

        recordPaymentService.findPage(pageNum,pageSize,$scope.searchEntity).success(function (response) {

            if (response.code == 200){
                $scope.recordPaymentList = response.data;
            } else {
                $scope.recordPaymentList = [];
            }
        });

    };

    //获取任务明细记录列表
    $scope.findTaskInfo = function (taskBatchNo) {

        let pageNum = 1;

        let pageSize = 1000;

        $scope.searchEntity.taskBatchNo = taskBatchNo;

        taskInfoService.findPage(pageNum, pageSize, $scope.searchEntity).success(function (response) {

            if (response.code == 200) {
                $scope.taxTaskInfoList = response.data;

            } else {
                $scope.taxTaskInfoList = [];
            }
        });

    };

    $scope.tableExportExcel = function () {
//显示
        $('#loading').modal('show');
        invoiceBatchService.findPage(1,999,$scope.searchEntity).success(function (response) {

            if (response.code == 200){
                // 要导出的json数据
                let jsonData = response.data;
                // 列标题，逗号隔开，每一个逗号就是隔开一个单元格
                let str = `品牌,申请编号,申请时间,发票抬头,开票方,可开票金额（元）,申请开票金额（元）,剩余开票金额（元）,开票说明,状态,开票类目, 发票邮寄地址\n`;
                // 增加\t为了不让表格显示科学计数法或者其他格式
                const needs = ['brandName','applyNumber','createTime','invoiceRise','invoicer','invoiceTotalMoneyCopy',
                    'taxTotalMoneySum','difference','invoiceInstructions','invoiceStatus', 'invoiceServiceNames', 'mailInfo']
                for(let i = 0 ; i < jsonData.length ; i++ ){
                    for (let j = 0; j < needs.length; j++) {
                        let arr = needs[j]
                        if (arr === 'createTime') {
                            jsonData[i][arr] = $scope.myFormatDate(jsonData[i][arr], 'yyyy-MM-dd HH:mm:ss')
                        }
                        if (arr === 'invoiceStatus') {
                            jsonData[i][arr] = jsonData[i][arr] == 1 ? '待审核' : (jsonData[i][arr] == 2 ? '已邮寄' : jsonData[i][arr] == 3 ? '驳回' : '已开票')
                        }
                        if (arr === 'mailInfo') {
                            jsonData[i][arr] = jsonData[i][arr].detailedAddress + " " + jsonData[i][arr].recipientName + " " + jsonData[i][arr].recipientPhone
                        }
                        if (arr == 'brandName') {
                            jsonData[i][arr] = jsonData[i].brand.brandName;
                        }

                        str += `${jsonData[i][arr] + '\t'},`;
                    }
                    str+='\n';
                }
                //影藏
                $('#loading').modal('hide');
                //encodeURIComponent解决中文乱码
                let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
                //通过创建a标签实现
                var link = document.createElement("a");
                link.href = uri;
                //对下载的文件命名
                link.download =  "发票管理明细.csv";
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);

            } else {
                alert(response.msg)
            }
        });
    }
});